package com.itheima.controller;

/*
 *@AUTHOR:LIUCHAO;
 *@DATE: 2020/9/16 9:41
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.http.HttpResponse;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private LoginService loginService;
    @RequestMapping("/check")
    public Result login(HttpServletResponse response, @RequestBody Map map ){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String codeInRedis= jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        String telephoneInRedis =jedisPool.getResource().get("login"+telephone);
        if (!(telephone.equals(telephoneInRedis)&&validateCode.equals(codeInRedis))){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Result result = loginService.checkMember(telephone);
        if (result.isFlag()){/*成功登录后,记录cookie到session中,进行跟踪*/
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");/*路径*/
            cookie.setMaxAge(60*60*24*30);//有效期30天
            response.addCookie(cookie);
            Member member = (Member) result.getData();
            /*将会员信息转换成一个json数据格式,保存在redis中
            * 会员信息也是有时效的,超时之后需要重新登录*/
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
        }
        return result;
    }



}
